const options = {
  dbName: "page",
  version: 3,
  store: "table",
  primay: "id"
}


/** 使用 indexedDB 来实现数据的存储管理 */
class PageDataBase {
  #db;
  #name;

  constructor() {}

  /**
   * 打开数据库，只有接受到返回code为1的响应时，才表示数据库打开成功
   * @param {string} dbName 数据库名称
   * @param {number} dbVersion 数据库版本
   * @param {string} store 存储体名称
   * @param {string} primay 存储体主键
   * @returns {Promise<{ code: number, message: string, data: any}>}
   */
  async open(dbName, dbVersion, store, primay) {
    const self = this;
    return new Promise((resolve, reject) => {
      const result = window.indexedDB.open(dbName, dbVersion);

      result.onerror = (event) => {
        console.log("数据库打开错误:", event.target.errorCode);

        resolve({ code: 0, message: " 该浏览器不支持IndexedDB数据库 " });
      };

      result.onsuccess = () => console.log("数据库打开成功");;

      // 创建存储体，配置存储体主键0
      result.onupgradeneeded = (event) => {
        self.#db = event.target.result;
        self.#name = dbName;

        if (self.#db.objectStoreNames.contains(store)) {
          self.#db.deleteObjectStore(store);
        }

        self.#db.createObjectStore(store, { keyPath: primay });

        resolve({ code: 1, message: " 数据库打开成功 " });
      }
    })
  }

  save(store, data) {
    const self = this;
    return new Promise(resolve => {
      typeof data !== "object" && (data = { value: data });

      const request = self.#db.transaction(self.#name, "readwrite").objectStore(store).put(data);
      request.onerror = (event) => resolve({ code: 0, message: " 保存数据失败 " });
      request.onsuccess = (event) => resolve({ code: 1, message: " 保存数据成功 ", data: event.target.result });
    })
  }

  /**
   * 获取数据
   * @param {string} store 存储体名称
   * @param {string} key 需要获取的key
   */
  get(store, key) {
    return new Promise(resolve => {
      const transaction = this.#db.transaction(store, "readonly");
      const objectStore = transaction.objectStore(store);
      const request = objectStore.get(key);
      request.onerror = (event) => resolve({ code: 0, message: " 获取数据失败 " });
      request.onsuccess = (event) => resolve({ code: 1, message: " 获取数据成功 ", data: event.target.result });
    })
  }

  remove(store) {
    this.#db.deleteObjectStore(store);
  }
}